"""
配置管理模块
统一管理所有配置项，支持环境变量和配置文件
提供类型安全的配置访问
"""

import os
from typing import Optional
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """
    应用配置类
    使用pydantic进行配置验证和类型检查
    """

    # API配置
    dashscope_api_key: str = "sk-801866c8ee2e4f6faedbbfff89c3ece5"
    deepseek_api_key: Optional[str] = None  # 保留以避免配置错误，但标记为可选
    minmax_api_key: Optional[str] = None
    minmax_group_id: Optional[str] = None
    character_profile_api: str = (
        "http://127.0.0.1:3000/api/ai-persons/getCharacterProfile"
    )

    # JWT配置
    jwt_secret: str = "visitor_auth_secret_key_very_secure"
    jwt_expires_in: str = "20d"
    jwt_frontend_secret: str = "qqwwweerr"

    # 服务器配置
    host: str = "0.0.0.0"
    port: int = 8000
    debug: bool = False
    allowed_origins: str = "http://localhost:3000,http://localhost:5173"  # 添加CORS配置

    # 数据库配置
    database_url: str = "mysql+aiomysql://root:admin123@localhost:3306/knowyou"
    db_name: str = "knowyou"
    db_user: str = "root"
    db_password: str = "admin123"
    db_host: str = "localhost"
    db_port: int = 3306

    # Redis配置
    redis_url: str = "redis://localhost:6379"

    # HTTP客户端配置
    request_timeout: float = 30.0
    max_connections: int = 100
    max_keepalive_connections: int = 20

    # LLM配置
    default_llm_model: str = "deepseek-chat"
    temperature: float = 0.3  # 降低温度以提高语言一致性
    max_tokens: int = 300

    # TTS配置
    default_tts_model: str = "speech-01-hd"
    default_voice_id: str = "female-tianmei"

    # Token确认/取消API配置
    token_confirm_api: str = "http://127.0.0.1:3000/api/tokens/confirm"
    token_cancel_api: str = "http://127.0.0.1:3000/api/tokens/cancel"

    # ComfyUI服务器配置 - 支持多服务器负载均衡
    comfyui_servers: list = [
        "https://wp05.unicorn.org.cn:17611",
        # "https://wp01.unicorn.org.cn:20079",
    ]
    comfyui_api_key: str = (
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJbmZvIjoiYXBpOjE5Mzg1Mzg5ODIyOTg4OTQzMzYiLCJleHAiOjE3ODI1NTU4NDN9.q6cefoqsPWxiIzdu6vsmrCGgMhnKZoB2jtEU-tu1b9A"
    )

    # 缓存配置
    cache_ttl: int = 300  # 默认缓存5分钟
    max_cache_size: int = 1000  # 最大缓存条目数
    enable_caching: bool = True

    # 速率限制配置
    rate_limit_requests: int = 10  # 每分钟请求数
    rate_limit_window: int = 60  # 时间窗口（秒）

    # 日志配置
    log_level: str = "INFO"
    log_file: str = "logs/app.log"

    class Config:
        env_file = ".env"
        case_sensitive = False

    def get_api_base_url(self, service: str) -> str:
        """
        获取指定服务的API基础URL

        Args:
            service: 服务名称 (deepseek, minmax)

        Returns:
            str: API基础URL
        """
        if service == "deepseek":
            return "https://dashscope.aliyuncs.com/compatible-mode/v1"
        elif service == "minmax":
            return "https://api.minimax.chat/v1/t2a_v2"
        else:
            raise ValueError(f"未知的服务: {service}")


# 全局配置实例
settings = Settings()
